package com.tr.ssocms.service.Impl;

import com.tr.common.bo.User;
import com.tr.common.contant.LoginType;
import com.tr.common.util.CustomException;
import com.tr.common.util.JwtUtils;
import com.tr.common.util.Result;
import com.tr.common.util.ResultStatus;
import com.tr.ssocms.service.AuthenticationService;
import com.tr.ssocms.shiro.CustomUsernamePasspordToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service("remoteUserService")
public class RemoteUserServiceImpl implements AuthenticationService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result checkUsernameAndPassword(String userName, String passWord) {
        //判断同户名密码是否空
        if (!StringUtils.hasText(userName) || !StringUtils.hasText(passWord)) {
            throw new CustomException(ResultStatus.ARGUMENT_IS_NOT_NULL.getReturncode(),
                    ResultStatus.ARGUMENT_IS_NOT_NULL.getReturnMessage());
        }
        //手机用户信息
        CustomUsernamePasspordToken customUsernamePasspordToken = new CustomUsernamePasspordToken(userName, passWord, LoginType.USER.toString());
        //获取subject
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(customUsernamePasspordToken);
            //获取用户信息
            User user = (User) subject.getPrincipal();
//            String token = user.getUserName() + UUID.randomUUID().toString();
            String jwtToken = JwtUtils.getJwtToken(String.valueOf(user.getUserId()), String.valueOf(user.getUserName()));
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            log.info("Token值：{}",jwtToken);
            redisTemplate.opsForValue().set(jwtToken,user,60, TimeUnit.MINUTES);
            HashMap<String, String> map = new HashMap<>();
            map.put("token",jwtToken);
            map.put("userId",user.getUserId().toString());
//            return new Result(200,"登录成功！",map);
            // 设置放入redis后key序列化方式，使用字符串  key是是什么放入的就是什么
//            redisTemplate.setKeySerializer(new StringRedisSerializer());
            //存储新登录的token前，删除以前的token
//            Set keys = redisTemplate.keys(userName + "*");
//             循环删除
//            for (Object key : keys) {
//                redisTemplate.delete(key);
//            }
            //  使用Redis 字符串操作，放入对象  方便后面使用token换取用户信息
//            redisTemplate.opsForValue().set(token, user, 3, TimeUnit.DAYS);

            return new Result(ResultStatus.SUCCESS.getReturncode(), ResultStatus.SUCCESS.getReturnMessage(), map);

        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return new Result(ResultStatus.ERROR.getReturncode(),
                ResultStatus.ERROR.getReturnMessage(), "用户名或者密码错误！");
    }

    @Override
    public boolean checkToken(String token) {
        return redisTemplate.hasKey(token);
    }
}
